package client_updater


import db.Client
import org.mortbay.util.ajax.Continuation
import scala.collection.mutable.HashMap
import scala.collection.mutable.Queue

/**
 * Clients updater is responsible for handling all the updates to be sent to clients.<br>
 * It supports adding and getting an update for a client. 
 */
object ClientsUpdater {
  val hmUpdates = new HashMap[Long, Queue[Update]]
  val hmConts = new HashMap[Long, Continuation]

  /**
   * receives Long as client ID, and an update.<br>
   * stores the new update in a data structure, and if the client is now connected notifies him.
   * @param -client : Long, the id of the client
   * @param -update : Update, the update to be stored for the given client
   */
  def addUpdate(client: Long, update: Update) = {
    var value = hmUpdates.get(client)
    var queue : Queue[Update] = null
    if(!value.isEmpty)
      queue = value.get
    if (queue != null) {
      queue.enqueue(update)
    } else {
      queue = new Queue[Update]
      queue.enqueue(update)
      hmUpdates.put(client, queue)
      println("update: \""+update.mes+"\" added for user: cid="+client)
    }
    println(hmConts)
    val value2 = hmConts.get(client)
    var cont : Continuation = null
    if(!value2.isEmpty)
      cont = value2.get
    println(cont)
    if (cont != null){
      println("cc is not null")
      cont.resume()
    }
  }

  /**
   * @param -client : Long, the id of the client<br>
   * @returns - Update- an update for the given client
   */
  def getUpdate(client: Long): Update = {
    val value = hmUpdates.get(client)
    var queue : Queue[Update] = null
    if(!value.isEmpty)
      queue = value.get
    if (queue == null) {
      return null
    }
    var update = null.asInstanceOf[Update]
    if (!queue.isEmpty) {
      update = queue.dequeue
    }
    if (queue.isEmpty) {
      hmUpdates.remove(client)
    }
    return update
  }

  /**
   * receives Continuation and client ID, and stores them in a data structure,<br>
   * in order to notify the client when it has new updates.<br>
   * @param -cc : Continuation 
   * @param -client : Long, the id of the client
   */
  def addCont(cc: Continuation, client: Long) {
    if (hmConts.get(client) != null) {
      hmConts.remove(client)
    }
    if(cc!=null)println("puting cc")
    hmConts.put(client, cc)
    println("client: "+client+";cc:"+cc)
  }
}
